package com.eurasia.firstapp.services;

import com.eurasia.firstapp.entities.User;
import com.eurasia.firstapp.exceptions.BusinessException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {
    private static List<User> users = new ArrayList<>();

    public User register(String username, String password) throws BusinessException {
        if (isAlreadyExist(username)) {
            throw new BusinessException("username is already exist");
        }
        return addUser(username, password);
    }

    private User addUser(String username, String password) {
        User user = new User(username, password);
        users.add(user);
        return user;
    }

    private boolean isAlreadyExist(String username) {
        for (User user : users) {
            if (user.getUsername().equals(username)) {
                return true;
            }
        }
        return false;
    }

    public User login(String username, String password) throws BusinessException {
        User user = findByUsernameAndPassword(username, password);
        if (Objects.isNull(user)) {
            throw new BusinessException("username or password is wrong");
        }
        return user;
    }

    private User findByUsernameAndPassword(String username, String password) {
        for (User user : users) {
            if (user.getUsername().equals(username)
                && user.getPassword().equals(password)) {
                return user;
            }
        }
        return null;
    }
}
